package com.xh.hongaiagent.app;

import com.xh.hongaiagent.advisor.MyLoggerAdvisor;
import com.xh.hongaiagent.advisor.ReReadingAdvisor;
import com.xh.hongaiagent.chatememory.FileBasedChateMemory;
import com.xh.hongaiagent.rag.LoveAppDocumentLoader;
import com.xh.hongaiagent.rag.LoveAppRagCustomAdvisorFactory;
import com.xh.hongaiagent.rag.QueryRewriter;
import com.xh.hongaiagent.tools.ToolRegistration;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.RetrievalAugmentationAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.ToolCallbacks;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.stereotype.Component;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import reactor.core.publisher.Flux;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class LoveApp {

    private final ChatClient chatClient;

    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。\n";


    //本地RAG实现: springai中自带SimpleVectorStore  文档处理：切词，抽取元信息，增强转换 +
    @Resource
    private VectorStore loveAppVectorStore;

    @Resource
    private VectorStore pgVectorVectorStore;

    @Resource
    private Advisor loveAppRagCloudAdvisor;

    @Resource
    private Advisor loveAppVectorStoreAdvisor;


    @Resource
    private QueryRewriter queryRewriter;

    @Resource
    private ToolCallback[] allTools;

    /**
     * 初始化AI客户端
     * @param dashscopeChatModel
     */
    public LoveApp(ChatModel dashscopeChatModel){
        //SpringAi自带chatmemory
//        ChatMemory chatMemory = new InMemoryChatMemory();
        //使用kryo序列化，本地文件存储的chatmemory
        String fileDir = System.getProperty("user.dir")+"/tmp";
        ChatMemory chatMemory = new FileBasedChateMemory(fileDir);
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        //支持多轮对话记忆
                        new MessageChatMemoryAdvisor(chatMemory),
                        // 自定义日志拦截器
                        new MyLoggerAdvisor()
//                        // 自定义复读拦截器
//                        new ReReadingAdvisor()
                )
                .build();
    }

    /**
     * AI对话基础版（支持多轮对话记忆）
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    /**
     * AI对话基础版（支持多轮对话记忆）
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChatByStream(String message, String chatId) {
        Flux<String> content = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .stream().content();
        content.subscribe(content1-> log.info("content: {}", content1));

        return content;
    }

    record LoveReport(String title, List<String> suggestions){
    }


    /**
     * AI 恋爱报告生成
     * @param message
     * @param chatId
     * @return
     */
    public LoveReport doChatwithReport(String message, String chatId) {
        LoveReport loveReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后生成一个恋爱报告，标题为{用户名}的恋爱，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);
        log.info("LoveReport: {}", loveReport);
        return loveReport;
    }

    /**
     * Rag
     * @param message
     * @param chatId
     * @return
     */
    public String doChatwithRag(String message, String chatId) {
        // 重写增强查询
        String rewritedMessage = queryRewriter.rewriteQuery(message);

        ChatResponse response = chatClient.prompt()
                .user(rewritedMessage)
                //消息对话记忆
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
//                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))//.advisors(new RetrievalAugmentationAdvisor(loveAppVectorStore))
                //自定义向量数据库规则查询本地向量数据库
                .advisors(LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(loveAppVectorStore))
                // 基于云知识库RAG
//                .advisors(loveAppRagCloudAdvisor)
                //基于PgVector向量数据库的rag
//                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    /**
     * AI对话rag增强版（支持多轮对话记忆）
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChatWithRagByStream(String message, String chatId) {
        Flux<String> content = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                //自定义向量数据库规则查询本地向量数据库
                .advisors(LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(loveAppVectorStore))
                .stream().content();
        content.subscribe(content1-> log.info("content: {}", content1));

        return content;
    }

    /**
     * AI 恋爱报告生成（支持工具调用）
     * @param message
     * @param chatId
     * @return
     */
    public String doChatwithTools(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后生成一个标题为{用户名}的恋爱报告，内容为建议列表，并且以pdf格式保存")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .tools(allTools)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


    //AI调用MCP服务 自动整合所有mcp服务
    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    /**
     * AI 恋爱报告生成（支持工具调用）
     * @param message
     * @param chatId
     * @return
     */
    public String doChatwithMcp(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后生成一个标题为{用户名}的恋爱报告，内容为建议列表，并且以pdf格式保存")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 使用MCP服务
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }



}
